#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sysinfo.h>
#include <fcntl.h>
#include <getopt.h>
#include <string.h>

int main()
{
    struct sysinfo s_info;
    
    char buf[2048];
    char info_buff[100];
    int fd = -1;
    int local_n = -1;
    if ((fd=open("/proc/meminfo",O_RDONLY)) == -1)
    {
        perror("open file");
        _exit(EXIT_FAILURE);
    }

    lseek(fd,0L,SEEK_SET); //0L:long n = 0 SEEK_SET:the start of the file
    if ((local_n = read(fd,buf,sizeof buf - 1)) < 0) {
        printf("hello world");
        perror("/proc/meminfo");
        exit(EXIT_FAILURE);
    }
    char* head;
    char* tail;
    char namebuf[16];

    buf[local_n] = '\0';
      head = buf;
 
    // total = used + free + buff/cached
    // cached = cache + Sreclaimable
    while(1)
    {
        if(sysinfo(&s_info)==0)
        {
            printf("\ttotal\tused\tfree\tshared\tbuff/cache\tavailable\n");
            sprintf(info_buff,"mem:\t%.ld",s_info.totalram/1024); //mem: total
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",s_info.freeram/1024);// used(unfinished)
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",s_info.freeram/1024);// free
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",s_info.sharedram/1024);// shared
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",s_info.bufferram/1024);// buff/cache (unfinished)
            printf("%s\t",info_buff);
            printf("\n");
            sprintf(info_buff,"swap:\t%.ld",s_info.totalswap/1024);
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",(s_info.totalswap/1024)-(s_info.freeswap/1024));
            printf("%s\t",info_buff);
            sprintf(info_buff,"%.ld",s_info.freeswap/1024);
            printf("%s\t",info_buff);
            printf("\n");
           // stdout);
        }
        sleep(5);
    }
}